var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var adminsRouter = require('./routes/admins');
var salesmansRouter = require('./routes/salesmans');
var insuresRouter = require('./routes/insures');
var ordersRouter = require('./routes/orders');
var typesRouter = require('./routes/types');
var customersRouter = require('./routes/customers');
var claimsRouter = require('./routes/claims');
var saleClaimsRouter = require('./routes/saleClaims');
var imagesRouter=require('./routes/images');
var pageDataRouter = require('./routes/Home/Main') 

//通过mongoose去连接MongoDB
const mongoose = require('mongoose');
//设置要连接的mongodb服务器地址(stu-stytm：要连接的数据库名称)
const dbURI = 'mongodb://localhost:27017/insurance-server';
//连接数据库
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('connected', () => console.log(dbURI + '数据库连接成功'))

var app = express();

// 自定义跨域中间件
var allowCors = function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept,Authorization");//Authorization 允许身份验证跨域
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
};
app.use(allowCors);//使用跨域中间件

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


//匹配前端ajax的url接口的一级路径
app.use('/', indexRouter);
app.use('/users', usersRouter);


app.use('/admins', adminsRouter);  //管理
app.use('/salesmans', salesmansRouter);   //销售员
app.use('/insures', insuresRouter);  //保险产品
app.use('/orders', ordersRouter);  //订单
app.use('/types', typesRouter);  //保险类
app.use('/customers', customersRouter);   //客户
app.use('/claims', claimsRouter);   //管理员理赔
app.use('/saleClaims', saleClaimsRouter);  //销售员理赔
app.use('/images',imagesRouter)//图片上传
app.use('/page',pageDataRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// module.exports = app;
//更改启动命令：node app.js
app.listen(3000, () => console.log('3000端口启动成功'))
